/**
 * @Title: ShareContentDialog.java
 * @Package com.jiuyang.baoxian.widget
 * @Description: TODO(用一句话描述该文件做什么)
 * @author ChangJianlong
 * @date 2014-12-26 下午2:56:53
 * @version V1.0
 */
package com.bxd.baodan.widget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Handler;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bxd.baodan.R;
import com.bxd.baodan.util.ResourcesUtil;
import com.bxd.baodan.util.ShareUtil;
import com.bxd.baodan.util.Utils;


/**
 * @ClassName: ShareContentDialog
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author ChangJianlong
 * @date 2014-12-26 下午2:56:53
 *
 */
public class ShareContentDialog extends Dialog implements OnItemClickListener,
		View.OnClickListener {
	LayoutInflater inflater;
	public static final int WEBCHAT_FRENDS = 0;// 微信好友
	public static final int WEBCHAT_MOMENTS = 1;// 微信朋友圈
	public static final int QQ_FRENDS = 2;// QQ好友
	public static final int QZONE = 3;// QQ空间
	public static final int WEIBO_SINA = 4;// 新浪微博
	// public static final int WEIBO_TENCENT = 5;// 腾讯微博
	public static final int MESSAGE = 5;// 短信分享
	public static final String SHARE_WECHAT_APP = "com.tencent.mm";
	public static final String SHARE_QQ_APP = "com.tencent.mobileqq";
	public static final String SHARE_QQ_ZONE = "com.qzone";
	public static final String SHARE_WEIBO_SINA = "com.sina.weibo";
	public static final String SHARE_WEIBO_TENCENT = "com.tencent.WBlog";
	private GridView gv;
	private Button cancel;
	private String content;
	private String title;
	private String url;
	private String imgUrl;
	private String id;
	private Handler handler;
	private String[] sharePlatForm = { "微信好友", "朋友圈", "QQ好友", "QQ空间"
            /*,"新浪微博",
			"短信"*/ };
	private int[] icons = { R.drawable.wx, R.drawable.pyq, R.drawable.qq,R.drawable.kj
            /*,R.drawable.sina, R.drawable.msg */};
	 /** 微博微博分享接口实例 */
//    private IWeiboShareAPI  mWeiboShareAPI = null;


	/**
	 * @param activity
	 *            上下文
	 * @param title
	 *            分享的标题
	 * @param content
	 *            分享的內容
	 * @param url
	 *            分享的url
	 * @param imgUrl
	 *            分享时候用到的图标
	 * */
	public ShareContentDialog(Activity activity, String title, String content,
			String url, String imgUrl, String id, Handler handler) {
		super(activity);
		inflater = LayoutInflater.from(activity);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.plugin_share_content);
		this.title = title;
		this.content = content;
		this.url = url;
		this.imgUrl = imgUrl;
		this.handler = handler;
		this.id=id;
		WindowManager m = activity.getWindowManager();
		Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
		WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
		p.width = (int) (d.getWidth() * 0.95); // 宽度设置为屏幕的0.95
		this.getWindow().setAttributes(p);
		this.getWindow().getAttributes().gravity = Gravity.CENTER;
		initViews();
	}

	/**
	 * 初始化组件和事件
	 * */
	private void initViews() {

		cancel = (Button) this.findViewById(R.id.cancelButton);
		gv = (GridView) this.findViewById(R.id.share_gridview);
		gv.setAdapter(new GridViewAdapter());
		cancel.setOnClickListener(this);
		gv.setOnItemClickListener(this);
	}

	class GridViewAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return sharePlatForm.length;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.grid_item_share, null);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.type_item_img);
				holder.text = (TextView) convertView
						.findViewById(R.id.type_item_text);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.text.setText(sharePlatForm[position]);
			holder.image.setImageResource(icons[position]);
			return convertView;
		}
	}

	class ViewHolder {
		public TextView text;
		public ImageView image;
	}

	/**
	 * toast提示应用未安装
	 *
	 * */
	private void showToastNoApp() {
		Toast.makeText(getContext(),
				ResourcesUtil.getStringById(R.string.notInstall),
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		boolean isAppInstalled = false;
		ShareUtil.initImagePath(getContext());
		switch (arg2) {
		case ShareContentDialog.WEBCHAT_FRENDS:
			if (Utils.isAvilible(this.getContext(), SHARE_WECHAT_APP)) {
				ShareUtil.shareMsgUrlToWeiXinHaoYou(content, title, url,
						imgUrl, this.getContext(), id, handler);
				isAppInstalled = true;
			}
			break;
		case ShareContentDialog.WEBCHAT_MOMENTS:
			if (Utils.isAvilible(this.getContext(), SHARE_WECHAT_APP)) {
				ShareUtil.shareMsgUrlToWeiXinPengYouQuan(content, title, url,
						imgUrl, this.getContext(), id, handler);
				isAppInstalled = true;
			}
			break;
		case ShareContentDialog.QQ_FRENDS:
			if (Utils.isAvilible(this.getContext(), SHARE_QQ_APP)) {
				ShareUtil.shareMsgUrlToQQHaoYou(content, title, url, imgUrl,
						this.getContext(), id, handler);
				isAppInstalled = true;
			}
			break;
		case ShareContentDialog.QZONE:
			if (Utils.isAvilible(getContext(), SHARE_QQ_ZONE)) {
				ShareUtil.shareMsgUrlToQQQZone(content, title, url, imgUrl,
						this.getContext(), id, handler);
				isAppInstalled = true;
			}
			break;
		case ShareContentDialog.WEIBO_SINA:

			 // 创建微博分享接口实例
//	        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(getAty(), Constant.APP_KEY);
//	        mWeiboShareAPI.registerApp();

//			System.out.println(title);
//			System.out.println(url);
//			System.out.println(imgUrl);
			if (Utils.isAvilible(getContext(), SHARE_WEIBO_SINA)) {

//				sendMessage();
				ShareUtil.shareMsgUrlToSinaWeiBo(content, title, url, imgUrl,
						this.getContext(), id, handler);
				isAppInstalled = true;
			}
			break;

		// 111
		// case ShareContentDialog.WEIBO_TENCENT:
		// if (Utils.isAvilible(this.getAty(), SHARE_WEIBO_TENCENT)) {
		// ShareUtil.shareMsgUrlToTencentWeiBo(content, title, url,
		// imgUrl, this.getAty());
		// isAppInstalled = true;
		// }
		// break;
		case ShareContentDialog.MESSAGE:
			ShareUtil.shareMsgUrlToMessage(content, title, url, imgUrl,
					this.getContext(), id, handler);
			isAppInstalled = true;
			break;
		default:
			break;
		}
		if (!isAppInstalled) {
			showToastNoApp();
			return;
		}
		// 取消dialog
		this.cancel();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.cancelButton:
			ShareContentDialog.this.cancel();
			break;
		default:
			break;
		}
	}


	/**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * @see {@link #sendMultiMessage} 或者 {@link #sendSingleMessage}
     *//*
    private void sendMessage() {
            if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
                int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
                if (supportApi >= 10351 ApiUtils.BUILD_INT_VER_2_2) {
                    sendMultiMessage();
                } else {
                    sendSingleMessage();
                }
            } else {
                Toast.makeText(getAty(), R.string.weibosdk_demo_not_support_api_hint, Toast.LENGTH_SHORT).show();
            }
       
    }
    
	@Override
	public void onResponse(BaseResponse baseResp) {
		// TODO Auto-generated method stub
		switch (baseResp.errCode) {
		case WBConstants.ErrorCode.ERR_OK:
			Toast.makeText(getAty(),
					R.string.weibosdk_demo_toast_share_success,
					Toast.LENGTH_LONG).show();
			break;
		case WBConstants.ErrorCode.ERR_CANCEL:
			Toast.makeText(getAty(),
					R.string.weibosdk_demo_toast_share_canceled,
					Toast.LENGTH_LONG).show();
			break;
		case WBConstants.ErrorCode.ERR_FAIL:
			Toast.makeText(
					getAty(),
					R.string.weibosdk_demo_toast_share_failed
							+ "Error Message: " + baseResp.errMsg,
					Toast.LENGTH_LONG).show();
			break;
		}
	}
	
	 *//**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 注意：当 {@link IWeiboShareAPI#getWeiboAppSupportAPI()} >= 10351 时，支持同时分享多条消息，
     * 同时可以分享文本、图片以及其它媒体资源（网页、音乐、视频、声音中的一种）。
     *
     * @param hasText    分享的内容是否有文本
     * @param hasImage   分享的内容是否有图片
     * @param hasWebpage 分享的内容是否有网页
     * @param hasMusic   分享的内容是否有音乐
     * @param hasVideo   分享的内容是否有视频
     * @param hasVoice   分享的内容是否有声音
     *//*
    private void sendMultiMessage() {
        
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
            weiboMessage.textObject = getTextObj();
        
            weiboMessage.imageObject = getImageObj();
        
        // 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
            weiboMessage.mediaObject=getWebpageObj();
        
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        // 3. 发送请求消息到微博，唤起微博分享界面
        System.out.println((Activity)constant);
        mWeiboShareAPI.sendRequest((Activity)constant, request);
    }

    *//**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 当{@link IWeiboShareAPI#getWeiboAppSupportAPI()} < 10351 时，只支持分享单条消息，即
     * 文本、图片、网页、音乐、视频中的一种，不支持Voice消息。
     *
     * @param hasText    分享的内容是否有文本
     * @param hasImage   分享的内容是否有图片
     * @param hasWebpage 分享的内容是否有网页
     * @param hasMusic   分享的内容是否有音乐
     * @param hasVideo   分享的内容是否有视频
     *//*
    private void sendSingleMessage() {
        
        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();
            weiboMessage.mediaObject = getTextObj();
            weiboMessage.mediaObject = getImageObj();
//            weiboMessage.mediaObject=
            weiboMessage.mediaObject = getWebpageObj();
        
        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;
        
        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest((Activity)constant, request);
    }
    
    
    *//**
     * 获取分享的文本模板。
     *
     * @return 分享的文本模板
     *//*
    private String getSharedText() {
        int formatId = R.string.weibosdk_demo_share_text_template;
        String format = getAty().getString(formatId);
        String text = format;
        return text;
    }
    
    
    *//**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     *//*
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = getSharedText();
        return textObject;
    }

    *//**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     *//*
    private ImageObject getImageObj() {
        final ImageObject imageObject = new ImageObject();
//        BitmapDrawable bitmapDrawable = (BitmapDrawable) mImageView.getDrawable();
//        imageObject.setImageObject(bitmapDrawable.getBitmap());
        DisplayImageOptions options;
		options = new DisplayImageOptions.Builder()  
		.showImageOnFail(R.drawable.empty_avatar) //加载失败的时候显示的图片
	    .showImageForEmptyUri(R.drawable.empty_avatar)  // 设置图片Uri为空或是错误的时候显示的图片  
	    .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中  
	    .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中  
	    .build();   
		ImageLoader imageLoder = ImageLoader.getInstance();
		imageLoder.loadImage(imgUrl, options, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String arg0, View arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
				// TODO Auto-generated method stub
//				Drawable drawable = getAty().getResources().getDrawable(R.drawable.empty_avatar);
//				BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; 
//				Bitmap bitmap = bitmapDrawable.getBitmap(); 
//				imageObject.setImageObject(bitmap);
			}
			
			@Override
			public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
				// TODO Auto-generated method stub
				 imageObject.setImageObject(arg2);
			}
			
			@Override
			public void onLoadingCancelled(String arg0, View arg1) {
				// TODO Auto-generated method stub
				
			}
		});
        
        return imageObject;
    }

    *//**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     *//*
    private WebpageObject getWebpageObj() {
    	System.out.println("---------->>");
    	System.out.println(title);
    	System.out.println(title);
    	System.out.println(url);
        final WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description =title;
//        
//        // 设置 Bitmap 类型的图片到视频对象里
//        mediaObject.setThumbImage(mShareWebPageView.getThumbBitmap());
        
        DisplayImageOptions options;
		options = new DisplayImageOptions.Builder()  
		.showImageOnFail(R.drawable.empty_avatar) //加载失败的时候显示的图片
	    .showImageForEmptyUri(R.drawable.empty_avatar)  // 设置图片Uri为空或是错误的时候显示的图片  
	    .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中  
	    .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中  
	    .build();   
		ImageLoader imageLoder = ImageLoader.getInstance();
		imageLoder.loadImage(imgUrl, options, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String arg0, View arg1) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
				// TODO Auto-generated method stub
				
				mediaObject.setThumbImage(arg2);
			}
			
			@Override
			public void onLoadingCancelled(String arg0, View arg1) {
				// TODO Auto-generated method stub
				
			}
		});
        mediaObject.actionUrl = url;
        mediaObject.defaultText = "Webpage 默认文案";
        System.out.println(mediaObject);
        System.out.println(mediaObject.title);
        System.out.println(mediaObject.description);
        System.out.println(mediaObject.actionUrl);
        return mediaObject;
    }*/

    /**
	 * 设置头像圆角显示
	 * @param avatar
	 * @param imageview
	 */
//	public static void setAvatarToRounderCorner(final Context context, String avatar, final ImageObject imageview) {
//		DisplayImageOptions options;
//		options = new DisplayImageOptions.Builder()  
//		.showImageOnFail(R.drawable.empty_avatar) //加载失败的时候显示的图片
//	    .showImageForEmptyUri(R.drawable.empty_avatar)  // 设置图片Uri为空或是错误的时候显示的图片  
//	    .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中  
//	    .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中  
//	    .build();   
//		ImageLoader imageLoder = ImageLoader.getInstance();
//		
//		imageLoder.loadImage(avatar, options,
//				new ImageLoadingListener(){
//					@Override
//					public void onLoadingCancelled(String arg0, View arg1) {
//						// TODO Auto-generated method stub
//					}
//					@Override
//					public void onLoadingComplete(String arg0, View arg1,
//							Bitmap arg2) {
//						// TODO Auto-generated method stub
//						//设置图片圆角DensityUtil.dip2px(context, 10))
//					    if (arg2 != null) {
//					    	imageview.setImageBitmap(arg2);
//					    }
//					}
//					@Override
//					public void onLoadingFailed(String arg0, View arg1,
//							FailReason arg2) {
//						// TODO Auto-generated method stub
//						Drawable drawable = context.getResources().getDrawable(R.drawable.empty_avatar); 
//						BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; 
//						Bitmap bitmap = bitmapDrawable.getBitmap(); 
//						imageview.setImageBitmap(bitmap);
//					}
//					@Override
//					public void onLoadingStarted(String arg0, View arg1) {
//						// TODO Auto-generated method stub
//					}
//				
//			});
//	}

}
